package com.oreilly.ez.service.impl;

import com.oreilly.ez.entity.Course;
import com.oreilly.ez.repo.CourseRepo;
import com.oreilly.ez.service.CourseService;
import com.oreilly.ez.util.CloneUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.info.ProjectInfoProperties;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Service
public class CourseServiceImpl  implements CourseService{


    @Autowired
    private CourseRepo courseRepo;

    @Override
    public Course save(Course item) {

        // is update ??
        Integer sid = item.getSid();
        if(sid != null){
            Course dbItem = courseRepo.getOne(sid);

            CloneUtils.copyProperties(item, dbItem);
            CloneUtils.copyProperties(dbItem, item);

        }

        return courseRepo.save(item);

    }

    @Override
    public void remove(Integer sid) {

        courseRepo.deleteById(sid);
    }


    @Override
    public Page<Course> find(Course item, Pageable pageable) {

        Specification<Course> specification = (root, query, criteriaBuilder) -> {

            List<Predicate> list = new ArrayList<>();
            String sname = item.getSname();
            if(StringUtils.isNotBlank(sname)){

                list.add(criteriaBuilder.like(root.get("sname").as(String.class), "%" + sname + "%"));
            }

            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        return courseRepo.findAll(specification, pageable);
    }

    @Override
    public Course findOne(Integer sid) {

        return courseRepo.findById(sid).get();
    }


}
